// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,
  Popconfirm,
  Upload,
  message,
  Button,
  Modal,
  Row,
  Col,
  Input,
  Divider,
  Tooltip,
  Icon,
  Tabs,
  Spin,
  Select,
  Radio,
  DatePicker } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config' 
import Cookie from 'js-cookie'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './countySetStyle.less' 
import ListPage from 'widget/PageTmpl/ListPageQiance'
import cx from 'classnames'
const { RangePicker } = DatePicker;
import moment from 'moment';
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
const confirm = Modal.confirm;
const FormItem = Form.Item
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
}
const formItemLayoutTime = {
  labelCol: { span: 0 },
  wrapperCol: { span: 16 },
}
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const countySetView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let  {biz,areaList,cityList,modalObj,detail} = modelObj

  function updateModal(type,item){
    modalObj.visible = !modalObj.visible;
    if(type){
      modalObj.type = type;
    }else{
      modalObj.type = "";
    }
    form.resetFields();
    if(item){
      detail.id = item.id;
      detail.area = item.area;
      detail.areaId = item.areaId;
      detail.cityId = item.cityId;
      detail.city = item.city;
      detail.createBy = item.createBy;
      detail.createTime = item.createTime;
      detail.region = item.region;
      detail.cityStatus = item.cityStatus;
      dispatch({
        type: `${namespace}/findByCity`,
        payload:{areaId:item.areaId}
      })
    }else{
      detail = {
        cityStatus:'1'
      };
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj,detail }
    })
  }

  function inputChange(value, type) {
    if(type == "areaId"){
      detail.cityId = "";
      let data = areaList.filter(item=>{
        return item.value == value
      })
      detail.area = data[0].label;
      dispatch({
        type: `${namespace}/findByCity`,
        payload:{areaId:value}
      })
    }else if(type == "cityId"){
      let data = cityList.filter(item=>{
        return item.value == value
      })
      detail.city = data[0].label;
    }else if(type == "cityStatus"&&value=='0'){
      detail.region = ''
    }
    detail[type] = value
    form.resetFields();
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { detail }
    })
  }

  function addOrEditDetail(){
    form.validateFields((err, values) => {
		  if(!err){
        dispatch({
          type: `${namespace}/addOrEditDetail`,
          payload:{actionType:modalObj.type,resetFields}
        })
		  }
		});
  }

  function deleteSkip(id){
    confirm({
      title: '删除确认',
      content: '您真的要删除此条数据吗?',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: `${namespace}/deleteFun`,
          payload:{id:id}
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': `${config.aheadPlan}cityConfig/CityConfig/list`,
      // 'api_url': 'admin/member/list',
      // 接口方式
      'method': 'GET',
      'app': '',
      // 接口参数
      'params': {
        pageSize:10,
        pageNo:1,
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'areaId',
            zh_name: '区域',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            cmpt_items: areaList
          },
          {
            en_name: 'cityId',
            zh_name: '城市',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            cmpt_items: cityList,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.areaId){
                dispatch({
                  type: `${namespace}/findByCity`,
                  payload:{areaId:biz.queryForm.areaId}
                })
              }
            }
          },
          {
            en_name: 'region',
            zh_name: '区/县',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'cityStatus',
            zh_name: '是否纳入月报统计',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            showSearch: true,
            cmpt_items: [
              {
                value: '',
                label: '全部'
              }, 
              {
                value: '1',
                label: '是'
              }, 
              {
                value: '0',
                label: '否'
              }, 
            ],
          },
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          // console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          // console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': '',
        'status_text': '全部',
        'scroll': { x: 1300 },
        // 表头字段列表"
        'fields': [
          {
            en_name: "key",
            zh_name: "序号",
            width: 80,
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            'en_name': 'area',
            'zh_name': '区域',
            width: 300
          },
          {
            'en_name': 'city',
            'zh_name': '城市',
            width: 200
          },
          {
            'en_name': 'region',
            'zh_name': '区/县',
            width: 200
          },
          {
            'en_name': 'createTime',
            'zh_name': '创建时间',
            width: 400
          },
          {
            'en_name': 'createBy',
            'zh_name': '创建人',
            width: 300
          },
          {
            'en_name': 'cityStatus',
            'zh_name': '是否纳入月报统计',
            render:(a, item, index, d, e, f)=>{
              if(item.cityStatus == '0'){
                return '否'
              }else if(item.cityStatus == '1'){
                return '是'
              }
            },
            width: 200
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 150,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  <FlagBtn node={<a onClick={() => updateModal('edit', item)}>编辑<span className="ant-divider"  style={{ display: 'inline-block' }}/></a>} btnId={''}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => deleteSkip(item.id)}>删除</a>} btnId={''}> </FlagBtn>
                </span>
              )
            },
          }

        ],
        'actions': [
        ],
        "action_props": {
          fixed: "right",
          width: 210
        }
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增',
          'btnId': '',
          'type': 'primary',
          'onClick': (e) => {
            updateModal('add');
          }
        }
      ]
    },
  }

  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }

  return (
      <div className={cx('pageLayout')}>
        <ListPage pageProps={pageProps} />
        <Modal
        title={modalObj.type=='edit'?'编辑':modalObj.type=='add'?'新增':'查看'}
        width='460px'
        visible={modalObj.visible}
        onOk={() => {modalObj.type == 'edit' || modalObj.type == 'add'?addOrEditDetail():updateModal()}}
        onCancel={() => { updateModal() }}
      >
        <div className={styles.detailContainer}>
          <Form>
            <Row>
            <Col span={20}>
                <FormItem
                  {...formItemLayout2}
                  label="区域">
                  {getFieldDecorator('areaId', {
                    initialValue: detail.areaId ? detail.areaId : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请选择区域' }
                    ], 
                  })(<Select
                  onChange={(e) => inputChange(e, 'areaId')}>
                  {areaList.map((item,idx)=>{
                      return <Select.Option key={item.key}  value={item.value}>{item.label}</Select.Option>
                    })}
                  
                </Select>)}
                </FormItem>
              </Col>
              <Col span={20}>
                <FormItem
                  {...formItemLayout2}
                  label="城市">
                  {getFieldDecorator('cityId', {
                    initialValue: detail.cityId ? detail.cityId : '',
                    rules: [
                      { required: modalObj.visible, whitespace: true, message: '请选择城市' }
                    ],
                  })(<Select
                    onChange={(e) => inputChange(e, 'cityId')}>
                    {cityList.map((item,idx)=>{
                      return <Select.Option key={idx}  value={item.value}>{item.label}</Select.Option>
                    })}
                  
                </Select>)}
                </FormItem>
              </Col>
              <Col span={20}>
                <FormItem label='是否纳入月报统计'  {...formItemLayout2}>
                  {getFieldDecorator('cityStatus', {
                    rules: [{
                      required: true, whitespace: true, message: '请选择是否纳入月报统计'
                    }],
                    initialValue: detail.cityStatus
                  })(
                    <Radio.Group name="cityStatus"  onChange={(e) => { inputChange(e.target.value, 'cityStatus') }}>
                        <Radio value="1">是</Radio>
                        <Radio value='0'>否</Radio>
                    </Radio.Group>
                  )}
                </FormItem>
              </Col>
              <Col span={20}>
                <FormItem
                  {...formItemLayout2}
                  label="区/县">
                  {getFieldDecorator('region', {
                    initialValue: detail.region ? detail.region : '',
                    rules: [
                      { required: false, whitespace: true, message: '请输入区/县' }
                    ],
                  })(<Input
                    placeholder={'请输入区/县'}
                    disabled={detail.cityStatus!='1'} 
                    onChange={(e) => { inputChange(e.target.value, 'region') }}
                  />)}
                </FormItem>
              </Col>
            </Row>
            <div style={{color: 'red'}}>注：若城市无法查找所需区/县，请在此新增</div>
          </Form>
        </div>
      </Modal>
      </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(countySetView))
